import sqlite3
from GLOBALPATH import Global


class SqliteOp(object):

    def __init__(self, db_path=Global.word2vec_db_path):
        self.db_path = db_path
        # conn = sqlite3.connect('./test.db')

    def operate(self, sql):
        db = sqlite3.connect(self.db_path)
        cur = db.cursor()
        try:
            # 执行sql语句
            cur.execute(sql)
            cur.close()
            # 提交到数据库执行
            db.commit()
        except Exception as e:
            print(e)
            cur.close()
            # Rollback in case there is any error
            db.rollback()
        # 关闭数据库连接
        db.close()

    def select(self, sql):
        db = sqlite3.connect(self.db_path)
        cur = db.cursor()
        results = None
        try:
            # 执行sql语句
            cur.execute(sql)
            # 获取所有记录列表
            results = cur.fetchall()
            # print(results)
        except Exception as e:
            print(e)
            # 关闭数据库连接
        db.close()
        return results


if __name__ == '__main__':
    # 使用之前先建张表，可以用cmd、navicat或者直接sqlt.operate创建也行，我是用navicat建的表

    sqlt = SqliteOp()

    sqlt.operate('''
        INSERT INTO `spider_list` (`name`, `state`) VALUES ("中国图书网", 0)
    ''')

    sqlt.select('''SELECT * FROM `spider_list` WHERE `name`="中国图书网"''')

